Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

312
Vistas
Debugging React/Flask connection with SyntaxError: Unexpected token < in JSON at position 0

I'm following https://blog.miguelgrinberg.com/post/how-to-create-a-react--flask-project attempting to connect a simple Flask backend with ReactJS after using npx create-react-app and adding a single flask file.

package.json

I've set up a proxy at "proxy": "http://localhost:5000" with a new script command of yarn start-backend.

  "scripts": {
    "start": "react-scripts start",
    "start-backend": "cd app && python3 app.py",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

nav.js

I've set up a Button using MaterialUI that calls a function to log a JSON response.

class Nav extends React.Component {

    clicked() {
        fetch('/').then(res => {
            console.log(res.json());
        }).then(data => {
            console.log(data);
        })
    }

    render() {
        return (
            <Box sx={{ flexGrow: 1}}>
                <AppBar position="static">
                    <Toolbar>
                        <SignUpForm onClick={() => this.clicked()} />
                    </Toolbar>
                </AppBar>
            </Box>
        )
    }
}

In the top level directory I've created a directory called app that has an app.py file with the following code.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return {"msg": "homepage from the backend."}

if __name__ == "__main__":
    app.run(port=5000, debug=True)

When I use yarn start and yarn start-backend and click the button, I get the error below

Promise {<pending>}
nav.js:14 undefined
VM1769:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Attempting to debug, but I'm unfortunately not getting anywhere. There's related questions but nothing seems to work. I've tried moving the flask file to the top level directory, to public, using http://localhost:5000/.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

fetch('/', {
     headers : { 
          'Content-Type': 'application/json',
          'Accept': 'application/json'
         }
}).then(res => {
            console.log(res.json());
        }).then(data => {
            console.log(data);
        })

about 4 years ago · Juan Pablo Isaza Denunciar

0

Ok, so being new to JavaScript/ReactJS it seems like I was missing two things

  1. I didn't have a return for the Promise which seems odd in that I thought you didn't have to return things

and

  1. Changing the path from / to /api/test seems to work.

I'll have to dig further to understand but for now it resolves my issue.

Here's the code that's changed

    clicked() {
        fetch('/api/test')
            .then(res => {return res.json()} )
            .then(
                data => {
                    console.log(data)
            })
    }

and


@app.route("/api/test")
def home():
    return {"msg": "homepage from the backend."}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda